<?php
// +----------------------------------------------------------------------
// | 作品管理
// +----------------------------------------------------------------------

namespace Admins\Controller;

use Common\Controller\AdminBase;

class WorksController extends AdminBase {

    //当前栏目id
    public $cateid = 0;

    public $workid=0;
    //模型缓存
    protected $model = array();

    //初始化模型
    protected function _initialize() {
        parent::_initialize();
        $this->cateid = I('request.cateid', $_POST['cateid'], 'intval');
        $this->workid = I('request.workid', $_POST['workid'], 'intval');

    }

    //首页
    public function index() {
        $this->display();
    }

    //显示栏目菜单列表
    public function public_categorys() {
        //是否超级管理员
        $json = array();
        $categorys = D('Admins/Category')->getData();
        foreach ($categorys as $rs) {
            $rs = getCategory($rs['cateid']);

            $data = array(
                'cateid' => $rs['cateid'],
                'parentid' => $rs['parentid'],
                'catename' => $rs['catename'],
            );
            //终极栏目
            if ($rs['child'] == 0) {
                $data['target'] = 'right';
                $data['url'] = U('Works/classlist', array('cateid' => $rs['cateid']));
                //设置图标
                $data['icon'] = self::$Cache['Config']['siteurl'] . 'static/js/zTree/zTreeStyle/img/diy/10.png';
            } else {
                $data['isParent'] = true;
            }

            $json[] = $data;
        }
        $this->assign('json', json_encode($json));
        $this->display();
    }

    //栏目信息列表
    public function classlist() {
        if (IS_POST) {
            $this->redirect('classlist', $_POST);
        }

        //当前栏目信息
        $cateInfo = getCategory($this->cateid);
        if (empty($cateInfo)) {
            $this->error('该栏目不存在！', U('Admins/Works/allworks'));
        }
        //排序
        $order=I('get.order','workid');
        //查询条件
        $where = array();
        if(isset($_GET['status']) && $_GET['status']==0)
            $status=0;
        else
        $status = I('get.status',1,'intval');
        $where['status'] = array('EQ', $status);
        $this->assign('statuss', $status);
        $where['cateid'] = array('EQ', $this->cateid);
        //搜索
        $search = I('get.search');
        if (!empty($search)) {
            $this->assign("search", $search);
            //添加开始时间
            $start_time = I('get.start_time');
            if (!empty($start_time)) {
                $start_time = strtotime($start_time);
                $where['create_time'] = array("EGT", $start_time);
                $this->assign('start_time', $start_time);
            }
            //添加结束时间
            $end_time = I('get.end_time');
            if (!empty($end_time)) {
                $end_time = strtotime($end_time);
                $where['create_time'] = array("ELT", $end_time);
                $this->assign('end_time', $end_time);
            }
            if ($end_time > 0 && $start_time > 0) {
                $where['create_time'] = array(array('EGT', $start_time), array('ELT', $end_time));
            }
            //类别
            $type = I('get.type', 0, 'intval');
            if(!empty($type)){
                $this->assign("type", $type);
                $where["type"] = array("EQ", (int) $type);
            }
            //搜索字段
            $searchtype = I('get.searchtype', null, 'intval');
            //搜索关键字
            $keyword = \Input::getVar(I('get.keyword'));
            if (!empty($keyword)) {
                $this->assign("searchtype", $searchtype);
                $this->assign("keyword", $keyword);
                if ($searchtype ==1) {
                    $where['title'] = array("LIKE", "%{$keyword}%");
                }elseif ($searchtype==2) {
                    $userid=M('User')->where(array('nickname'=>$keyword))->getField('userid');
                    $where['userid']=array('EQ',(int) $userid);
                } elseif ($searchtype == 3) {
                    $where["workid"] = array("EQ", (int) $keyword);
                }
            }
        }

        $model=M('Works');
        //信息总数
        $count = $model->where($where)->count();
        $page = $this->page($count, 20);
        $data = $model->where($where)->limit($page->firstRow . ',' . $page->listRows)->order(''.$order.' DESC')->select();

        $this->assign($cateInfo)
            ->assign('Page', $page->show())
            ->assign('cateid', $this->cateid)
            ->assign('count', $count)
            ->assign('data', $data);
        $this->display();
    }


    //添加信息
    public function add() {
        if (IS_POST) {
            //栏目ID
            $cateid = intval($_POST['cateid']);
            $post=$_POST;
            //获取当前栏目配置
            $category = getCategory($cateid);
            $model=D('Admins/Works');
            if ($category['child'] == 0) {
                $status = $model->addModel($post);
                if ($status) {
                    $this->success("作品添加成功！");
                } else {
                    $error = $model->getError();
                    $this->error($error ? $error : '添加失败！');
                }
            } else {
                $this->error("该栏目类型无法发布！");
            }
        } else {
            //取得对应栏目
            if(!empty($this->cateid)){
                $category = getCategory($this->cateid);
                if (empty($category)) {
                    $this->error('该栏目不存在！');
                }
                //判断是否终极栏目
                if ($category['child']) {
                    $this->error('只有终极栏目可以发布信息！');
                }
            }

            if ($category['type'] == 0) {
                $this->assign("cateid", $this->cateid);
                $this->assign("category", $this->getcategory_tree($this->cateid));
                $this->assign('create_time',time());
                $this->assign('endtime',time()+3600*24);
                $this->display();
            }
        }
    }

    /**
     * 编辑作品
     */
    public function edit(){
        if (IS_POST) {
        	$post = I('post.');
        	$post['image'] = $post['all_pic'][0];
        	if($post['all_pic'])
        	{
        		$arr = array();
        		foreach($post['all_pic'] as $k => $v)
        		{
        			if($k == 0 || !empty($v))
        			{
        				$arr[] = $v;
        			}
        		}
        		$post['all_pic'] = json_encode($arr);
        	}
        	if($post['status'] != 0)
        	{
        		$post['modify_time'] = time();
        	}
        	$data=$post;
            $model=D('Admins/Works');
            $status = $model->editModel($data);
            if ($status) {
                $this->success("作品更新成功！");
            } else {
                $error = $model->getError();
                $this->error($error ? $error : '更新失败！');
            }

        } else {
            if (empty($this->workid)) {
                $this->error('该作品不存在');
            }
            $works=D('Admins/Works')->relation(true)->find($this->workid);
            if(!empty($works['all_pic']))
            {
            	$pic = json_decode($works['all_pic'], true);
            	$arr = array();
            	foreach($pic as $k => $v)
            	{
            		$arr[$k]['thumb'] = $v;
            		$temp = explode("/", $v);
            		$temp[4] = str_replace("yf_", "", $temp[4]);
            		$arr[$k]['pic'] = implode("/", $temp);
            	}
            	$works['all_pic'] = $arr;
            }
            else
            {
            	$works['all_pic'][0]['thumb'] = $works['image'];
            	$works['all_pic'][0]['pic'] = $works['image'];
            }
           // print_r($works);
            usort($works['works_makestep'], function($a, $b)
            {
            	if($a['id'] <= $b['id'])
            	{
            		return 0;
            	}
            	else 
            	{
            		return ($a['id'] > $b['id']) ? 1 : -1;
            	}
            });//print_r($works);
            $this->assign('data',$works);
            //$this->assign("category", $this->getcategory_tree($works['cateid']));
            $category = M('Category')->where(array('parentid'=>0))->select();
            $twocate = M('Category')->where(array('parentid'=>$works['catfid']))->select();

            $this->assign('category',$category);
            $this->assign('twocate',$twocate);
            $this->display();

        }
    }


    /**
     * 显示默认列表页
     */
    public function allworks(){
        if (IS_POST) {
            $this->redirect('allworks', $_POST);
        }
        $order=I('get.order','workid');
        //查询条件
        $where = array();
        if(isset($_GET['status']) && $_GET['status']==0)
            $status=0;
        else
            $status = I('get.status',1,'intval');
        $where['status'] = array('EQ', $status);
        $this->assign('statuss', $status);

        //搜索
        $search = I('get.search');
        if (!empty($search)) {
            $this->assign("search", $search);
            //添加开始时间
            $start_time = I('get.start_time');
            if (!empty($start_time)) {
                $start_time = strtotime($start_time);
                $where['create_time'] = array("EGT", $start_time);
                $this->assign('start_time', $start_time);
            }
            //添加结束时间
            $end_time = I('get.end_time');
            if (!empty($end_time)) {
                $end_time = strtotime($end_time);
                $where['create_time'] = array("ELT", $end_time);
                $this->assign('end_time', $end_time);
            }
            if ($end_time > 0 && $start_time > 0) {
                $where['create_time'] = array(array('EGT', $start_time), array('ELT', $end_time));
            }
            //类别
            $type = I('get.type', 0, 'intval');
            if(!empty($type)){
                $this->assign("type", $type);
                $where["type"] = array("EQ", (int) $type);
            }
            //搜索字段
            $searchtype = I('get.searchtype', null, 'intval');
            //搜索关键字
            $keyword = \Input::getVar(I('get.keyword'));
            if (!empty($keyword)) {
                $this->assign("searchtype", $searchtype);
                $this->assign("keyword", $keyword);
                if ($searchtype ==1) {
                    $where['title'] = array("LIKE", "%{$keyword}%");
                }elseif ($searchtype==2) {
                    $userid=M('User')->where(array('nickname'=>$keyword))->getField('userid');
                    $where['userid']=array('EQ',(int) $userid);
                } elseif ($searchtype == 3) {
                    $where["workid"] = array("EQ", (int) $keyword);
                }
            }

        }
        $model=M('Works');
        //信息总数
        $count = $model->where($where)->count();
        $page = $this->page($count, 30);
        $data = $model->where($where)->limit($page->firstRow . ',' . $page->listRows)->order(''.$order.' DESC')->select();
        $this->assign('Page', $page->show())
            ->assign('cateid', $this->cateid)
            ->assign('count', $count)
            ->assign('data', $data);
        $this->display();
    }

    //删除产品
    public function delete(){
        $model=D('Admins/Works');
        $workid=I('get.workid','','intval');
        if($model->deleteModel($workid)){
            $item=M('Works')->field('userid,status,type,title,ifindex,iftj,modify_time')->where(array('workid'=>$workid))->find();
            if($item['type'] == 1){
                $upoint=20;
                $upcont="作品违规扣除20个积分";
            }else{
                $upoint=6;
                $upcont="参考作品违规扣除6个积分";
            }
            service('Passport')->userDynamic($item['userid'],$upoint,$upcont,0,'workadd');
            $this->success('成功删除作品');
        }else{
            $error=$model->getError();
            $this->error($error ? $error : '删除作品失败');
        }
    }


    //审核单个产品
    public function pass(){
        $workid=I('get.workid');
        if(empty($workid)){
            $this->error('审核失败');
        }
        $where['workid']=$workid;
        if(M('Works')->where($where)->setField(array('status'=>true, 'modify_time'=>time()))){
            $item=$this->field('userid,status,type,title,modify_time')->where($where)->find();
            if(empty($item['modify_time']))
            {   
                if($item['type'] == 1){
                    $upoint = 10;
                }else{
                    $upoint = 3;
                }
                $where['userid']= array('EQ',$item['userid']);
                $where['infoid']=array('EQ',$workid);
                $where['action']= array('EQ','workadd');
                $signnum=getCount('UserDynamic',$where);
                if($signnum == 0){
                    service('Passport')->userDynamic($item['userid'],$upoint, $item['title'],1,'workadd',$workid);
                }
            	
            }
            $this->success('审核成功');
        }else{
            $this->error('审核失败');
        }
    }


    //批量处理信息(审核,取消审核,删除)
    public function batch() {
        if (IS_POST) {
            $ids = $_POST['ids'];

            if (!$ids) {
                $this->error('没有信息被选中！');
            }
            $doAct=I('get.do');
            $today=date('Y年m月d日',time());
            switch($doAct){
                case 'checkpass':
                    $data=array('status'=>true,'modify_time' => time());
                    $msg='审核';
                    break;
                case 'cancelpass':
                    $data=array('status'=>false);
                    $msg='取消审核';
                    break;
                case 'nopass':
                    $data=array('status'=>2);
                    $msg='取消审核';
                    break;
                case 'checktj':
                    $data=array('iftj'=>true);
                    $msg='推荐';
                    break;
                case 'canceltj':
                    $data=array('iftj'=>false);
                    $msg='取消推荐';
                    break;
                case 'checkindex':
                    $data=array('ifindex'=>true);
                    $msg='首页';
                    break;
                case 'cancelindex':
                    $data=array('ifindex'=>false);
                    $msg='取消首页';
                    break;
            }
            foreach ($ids as $id) {
                $item=M('Works')->field('userid,status,type,title,ifindex,iftj,modify_time')->where(array('workid'=>$id))->find();

                M('Works')->where(array('workid'=>$id))->save($data);

                if($item['type']==1){
                    $upoint=10;
                }else{
                    $upoint=3;
                }

                if($doAct=='checkpass' && $item['status']!=true){
            
                	if(empty($item['modify_time']))
                	{
	                    $savearr['worksnum'] = array('exp','worksnum+1');

	                    $where['userid']= array('EQ',$item['userid']);
                        $where['infoid']=array('EQ',$id);
                        $where['action']= array('EQ','workadd');
                        $signnum=getCount('UserDynamic',$where);
                       
                        if($signnum == 0){
                            service('Passport')->userDynamic($item['userid'],$upoint, $item['title'],1,'workadd',$id);
                        }
	                    
	                    insertSysmsg($item['userid'],'恭喜作品通过审核','恭喜您的作品《'.$item['title'].'》于'.$today.'通过审核，继续努力哦！详情猛戳 <a href="http://www.hongbeiq.com">www.hongbeiq.com</a>');
                	}
                	else 
                	{
                		M('UserDynamic')->where(array('infoid'=>$id,'userid'=>$item['userid'],'action'=>'workadd'))->setField(array('status'=>true));
                	}
                }

                elseif($doAct!='checkpass' && $item['status']==true){

                    $savearr['worksnum'] = array('exp','worksnum-1');
                    $savearr['upoint'] = array('exp','upoint-'.$upoint.'');
                    M('UserDynamic')->where(array('infoid'=>$id,'userid'=>$item['userid'],'action'=>'workadd'))->setField(array('status'=>false));
                    M('Works')->where(array('workid' => $id))->save(array('modify_time' => 0)); 
                }
                M('User')->where(array('userid'=>$item['userid']))->save($savearr);

                //获取类别推荐
                if($doAct=='checktj' && $item['iftj']!=1 && $item['type'] == 1){

                    $where['userid']= array('EQ',$item['userid']);
                    $where['infoid']=array('EQ',$id);
                    $where['action']= array('EQ','worksclass');
                    $signnum=getCount('UserDynamic',$where);
                    if($signnum == 0){

                        service('Passport')->userDynamic($item['userid'],20,$item['title'].'推荐到分类获得20个积分',1,'worksclass',$id);    
                    }
                    
                    insertSysmsg($item['userid'],'恭喜作品获得头条推荐','恭喜您的作品《'.$item['title'].'》于'.$today.'被推荐到烘焙圈类头条，继续努力哦！详情猛戳 <a href="http://www.hongbeiq.com">www.hongbeiq.com</a>');
                }

                //获取首页推荐
                if($doAct=='checkindex' && $item['ifindex']!=1 && $item['type'] == 1){
                   
                    $where['userid']= array('EQ',$item['userid']);
                    $where['infoid']=array('EQ',$id);
                    $where['action']= array('EQ','worksindex');
                    $signnum=getCount('UserDynamic',$where);
                    if($signnum == 0){

                        service('Passport')->userDynamic($item['userid'],30,$item['title'].'推荐到首页获得30个积分',1,'worksindex',$id);
                    }

                    

                    insertSysmsg($item['userid'],'恭喜作品获得首页推荐','恭喜您的作品《'.$item['title'].'》于'.$today.'被推荐到烘焙圈首页，继续努力哦！详情猛戳 <a href="http://www.hongbeiq.com">www.hongbeiq.com</a>');
                }
            }
            $this->success($msg.'成功！');
        }
    }

    //批量排序
    public function batch_sort(){
        $ids = $_POST['ids'];
        if (!$ids) {
            $this->error('没有信息被选中！');
        }
        $Items = M('Works');
        foreach ($_POST['sort'] as $id => $sort) {
            $Items->where(array('workid' => $id))->save(array('sort' => $sort));
        }
        $this->success("排序更新成功！");
    }

    //批量删除
    public function batch_delete(){
        $ids = $_POST['ids'];
        if (!$ids) {
            $this->error('没有信息被选中！');
        }
        foreach($ids as $id){
                D('Admins/Works')->deleteModel($id);
                $item=M('Works')->field('userid,status,type,title,ifindex,iftj,modify_time')->where(array('workid'=>$id))->find();
                if($item['type'] == 1){
                    $upoint=20;
                    $upcont="作品违规扣除20个积分";
                }else{
                    $upoint=6;
                    $upcont="参考作品违规扣除6个积分";
                }
                service('Passport')->userDynamic($item['userid'],$upoint,$upcont,0,'workadd');
            }
        $this->success('成功删除作品');
    }

    /**
     * 删除材料
     */
    public function delmaterials(){
        $id=I('get.mtid',0,'intval');
        if(empty($id)){
            $this->error('删除请求失败');
        }
        if(M('works_materials')->where(array("id"=>$id))->delete()){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }

    /**
     * 删除操作步骤
     */
    public function delmakestep(){
        $id=I('get.stepid',0,'intval');
        $model=D('Admins/Works');
        $status=$model->deleteMakeStepModel($id);
        if($status!==false){
            $this->success("删除成功");
        }else{
            $error=$model->getError();
            $this->error($error ? $error : '删除失败');
        }

    }

    //获取栏目树形
    public function getcategory_tree($cateid){

        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;│ ', '&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;';
        $categorys = array();
        $categorysList=cache('Category');
        if(empty($categorysList)){
            $categorysList=D('Admins/Category')->getData();
        }else{
            $categorysList=cache('Category');
        }
        foreach ($categorysList as $cid => $r) {
            $r = getCategory($r['cateid']);
            $r['disabled'] = $r['child'] ? 'disabled' : '';
            $r['selected'] = $cid == $cateid ? 'selected' : '';
            $categorys[$cid] = $r;
        }
        $str = "<option value='\$cateid' \$selected \$disabled>\$spacer \$catename</option>";
        $tree->init($categorys);

        $string .= $tree->get_tree(0, $str);

        return $string;
    }

     //ajax获取作品的二级分类
    public function ajax(){
       $id = I('get.id');
       $category = M('Category')->where(array('parentid'=>$id))->order('cateid DESC')->select();
       if($category){
            $option = '';
            foreach ($category as $key => $value) {
               $option ="<option value='".$value['cateid']."'>".$value['catename']."</option>".$option;
            }
            echo $option;
       }else{

        echo "no";
       }

    }

}
